import { PureComponent } from "react";
import { Button, Modal,ActivityIndicator,InputItem,Accordion,List,SearchBar,TabBar} from "antd-mobile"
import { connect } from 'dva';
import { handleImg, goToPage,isNull,handleOSS } from "../../utils/helper";
import { Row, Col } from 'antd';
import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
import { Menu } from 'antd';
import MToast from '../../components/Util/MToast';
const { SubMenu } = Menu;
@connect(() => {
  return ({

  })
})
export default class Category extends PureComponent{

  constructor(props){
    super(props);
    this.state = {
      categoryItem:[],
      categoryChild:[],
      openKeys: [],
      rootSubmenuKeys:[],
      defaultSelectedKeys:[],
      code:'',
      goodsItem:[],
      loading:true,
      loading1:true,
      isDown:false,
      selectedTab: 'blueTab',
      isButton:false,
      isOpen:false
    }
  }
  componentWillMount(){
    let {dispatch,location} = this.props;
    let {categoryChild,openKeys} = this.state;
    localStorage.removeItem("codeKey");
    localStorage.removeItem("buttonCode")
    var arr=[];
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "qry/tree?_c=new_category_list",
          params: [
          ],
          _c: "new_category_list"
        },
        callback: (result) => {
          let { data } = result;
          data.map((i,k)=>{
            arr.push(i.code+ "")

          })

          this.setState({
            categoryItem:data,
            rootSubmenuKeys:arr,
            openKeys:[data[0].code + ""],
            defaultSelectedKeys:[data[0].code + ""],
            code:data[0].code,
            loading:false
          })
          console.log(openKeys,arr)
           this.handleClick(data[0].code)
        }
      }
    });

  }
  handleClick=(code)=>{
    let {dispatch,location} = this.props;
    let {loading,loading1} = this.state;

    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "qry/all?_c=app_category_goods_search",
          params: [
            {
              "key":"code",
              "value":code
            }
          ],
          _c: "app_category_goods_search"
        },
        callback: (result) => {
          let { data } = result;

          this.setState({
            goodsItem:data,
            loading1:false
          })


          console.log(data);

        }
      }
    });
  }
  handleDown=()=>{
    let {isDown}=this.state;
    this.setState({
      isDown:!this.state.isDown
    })
  }
  handleButton=(e,code)=>{
    console.log(code);
  localStorage.setItem("buttonCode",code)
    this.handleClick(code);

  }
  sidebarChild3=()=>{
    let {categoryItem,isDown,isButton}=this.state;
    return(
      categoryItem.map((i,k)=>{
        return(
          i.children.map((i,k)=>{
            if(i.code==localStorage.getItem("codeKey")){
              if(i.children.length<=3){
                return(
                  <Row style={{width:'100%'}}>{
                    i.children.map((i,k)=>{
                      return(
                        <Col span={7} key={i.code} style={{marginBottom:'0px',marginRight:'5px',}} className={i.code==localStorage.getItem("buttonCode")?"buttonColorHover1":''}>
                          <Button
                            className={i.code==localStorage.getItem("buttonCode")?"buttonColorHover":''}
                            style={{fontSize:'12px',height:'30px',lineHeight:'30px',background:'#F0F0F0', color:'#595867', border:'none'}}
                            onClick={(e)=>{
                              this.handleButton(e,i.code);
                            }}>{i.name}</Button>
                        </Col>
                      )
                    })
                  }

                  </Row>

                )

              }
              else{
                var arrChildren= i.children.slice(0,3);
                var arrChildrenAga= i.children.slice(3);
                console.log(arrChildren)
                return(
                  <Row style={{width:'100%',background:'#fff'}}>
                    <Row style={{width:'100%'}}>
                      {
                        arrChildren.map((i,k)=>{
                          return(
                            <Col span={6} key={i.code} style={{marginBottom:'10px',marginRight:'5px',}} className={i.code==localStorage.getItem("buttonCode")?"buttonColorHover1":''}>
                              <Button
                                className={i.code==localStorage.getItem("buttonCode")?"buttonColorHover":''}
                                style={{fontSize:'12px',height:'30px',lineHeight:'30px',background:'#F0F0F0', color:'#595867', border:'none'}}
                                onClick={(e)=>{
                                  this.handleButton(e,i.code)
                                }}>{i.name}</Button>
                            </Col>

                          )

                        })
                      }
                      <Col span={3} style={{marginLeft:'5px'}}><img src="image/arrow_bottom.png" style={{width:'24px',height:'24px'}} onClick={this.handleDown}/></Col>
                    </Row>
                    {
                      isDown?<Row style={{width:'100%',}}>
                        {i.children.map((i,k)=>{
                          return(
                            <Col span={6} key={i.code} style={{marginBottom:'10px',marginRight:'5px',}} className={i.code==localStorage.getItem("buttonCode")?"buttonColorHover1":''}>
                              <Button
                                className={i.code==localStorage.getItem("buttonCode")?"buttonColorHover":''}
                                style={{fontSize:'12px',height:'30px',lineHeight:'30px',background:'#F0F0F0', color:'#595867', border:'none'}}
                                onClick={(e)=>{
                                  this.handleButton(e,i.code)
                                  this.handleDown()
                                }}>{i.name}</Button>
                            </Col>

                          )
                        })}
                      </Row>:<Row style={{width:'100%',visibility:'hidden',height:'0px'}}>
                        {i.children.map((i,k)=>{
                          return(
                            <Col span={6} key={i.code} style={{marginBottom:'10px',marginRight:'5px',}} className={i.code==localStorage.getItem("buttonCode")?"buttonColorHover1":''}>
                              <Button
                                className={i.code==localStorage.getItem("buttonCode")?"buttonColorHover":''}
                                style={{fontSize:'12px',height:'30px',lineHeight:'30px',background:'#F0F0F0', color:'#595867', border:'none'}}
                                onClick={(e)=>{
                                  this.handleButton(e,i.code)
                                  this.handleDown()
                                }}>{i.name}</Button>
                            </Col>

                          )
                        })}
                      </Row>
                    }

                  </Row>

                )
              }
            }

          })
        )
      })
    )

  }
  sidebarChild=(menuChild)=>{
    if(menuChild.length!==0){

      return(
        menuChild.map((item,index)=>(
            <Menu.Item key={item.code}>
              {item.name}
            </Menu.Item>
          )
        )
      )



    }else{
      return (
        <div style={{ padding: "0px 0", textAlign: "center", fontSize: "20px", color: "#555" }}>
          {/*{T("No products(暂无分类)")}*/}
        </div>
      )
    }
  }
  sidebarMenu(){
    let {categoryItem,code,defaultSelectedKeys} = this.state;
    if (!categoryItem || categoryItem.length == 0) {
      return (
        <div style={{ padding: "40px 0", textAlign: "center", fontSize: "20px", color: "#555" }}>
          {T("No products(暂无商品)")}
        </div>
      )
    }
    else{
      return(
        <Menu
          onClick={this.handleSelect}
          style={{ width:'100%' }}
          mode="inline"
          defaultSelectedKeys={this.state.defaultSelectedKeys}
          openKeys={this.state.openKeys}
          onOpenChange={this.onOpenChange}
        >
          {categoryItem.map((i,k) => (

            <SubMenu
              key={i.code}
              title={
                <span><span>{i.name}</span></span>
              }>
              <Menu.Item  key={i.code} style={{fontWeight:'bold'}}>
                {i.name}
              </Menu.Item>

              {this.sidebarChild(i.children)}
              {/*{this.sidebarChild3(i.children)}*/}

            </SubMenu>
          ))}
        </Menu>
      )
    }
  }
  onOpenChange = openKeys => {
    let {categoryItem,rootSubmenuKeys}=this.state;

    const latestOpenKey = openKeys.find(key => this.state.openKeys.indexOf(key) === -1);
    if (rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      this.setState({ openKeys });
    } else {
      this.setState({
        openKeys: latestOpenKey ? [latestOpenKey] : [],
      });
    }
    //
    // categoryItem.map((i,k)=>{
    //   if(i.code==latestOpenKey){
    //     console.log(i);
    //     this.handleClick(i.code);
    //
    //   }else{
    //     console.log("xdfvdgrfg")
    //   }
    // })

  };

  handleSelect=(e)=>{
    let {categoryItem,isOpen} = this.state;
    localStorage.removeItem("buttonCode")
    console.log(e.key)
    localStorage.setItem("codeKey",e.key)
    categoryItem.map((i,k)=>{
      if(i.code==e.key){
        this.handleClick(i.code);
        this.setState({
          isOpen:false
        })
      }else{

      }
      i.children.map((item,index)=>{
        if(item.code==e.key){
          this.handleClick(item.code);
          if(item.children.length!==0){
            this.setState({
              isOpen:true
            })
          }else{
            this.setState({
              isOpen:false
            })
          }
        }else{

        }


      })


    })

  }
  handleDetail=(e,i)=>{
    let {dispatch} = this.props;
    goToPage({ dispatch, config: { url: "/goodsDetail?id="+i.id+"&store_id="+i.store_id }, isReplace: false })
  }
  handleAdd=(e,i)=>{
    console.log(i.img_url);
    let {dispatch} = this.props;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "cart/add",
          params: [
            {
              key: "goods_id",
              value: i.id
            },
            {
              key: "goods_name",
              value: i.goods_name
            },
            {
              key: "img_url",
              value: i.img_url
            },
            {
              key: "price",
              value: i.price
            },
            {
              key: "quantity",
              value: 1
            }
          ]
        },
        callback: (result) => {
          let { data } = result;
          console.log(data)
          MToast.info(T("È stato aggiunto un nuovo articolo al tuo carrello.（商品已加入到购物车）",3, null, false));

        }
      }
    })
  }
  renderList(){
    let {goodsItem,loading1} = this.state;
    if (!goodsItem || goodsItem.length == 0) {
      return (
        <div style={{ padding: "40px 0", textAlign: "center", fontSize: "20px", color: "#555" }}>
          {T("No products(暂无商品)")}
        </div>
      )
    }
    else{
      if (loading1) {
        return (
          <div className="normal">
            <ActivityIndicator toast text="正在加载" animating={true} />
          </div>
        )
      }else{
        return(
          <Row style={{marginBottom:'10px',padding:'0px 0px',}}>
            {goodsItem.map((i,k) => (
              <Row style={{borderBottom: "1px solid #ddd",width:'100%',margin:'5px 0',height:'85px'}} key={k} >
                <Col span={7} style={{margin:'5px 10px 0 0'}} onClick={(e)=>{this.handleDetail(e,i)}}><img src={handleOSS(i.img_url)} style={{width:'64px',height:'64px'}}/></Col>
                <Col span={12} onClick={(e)=>{this.handleDetail(e,i)}}>
                  <div className="ellipsis2" style={{marginBottom:'20px',color:'#595867',fontSize:'14px',height:'36px',marginTop:'5px'}}>{i.goods_name}</div>
                  <div style={{color:'#F09600',fontSize:'15px',fontWeight:'bold'}}>€{i.price}</div>
                </Col>
                <Col span={3} style={{marginTop:'47px',}} onClick={(e) => {this.handleAdd(e,i) }}><img src="image/cart1.png" style={{width:'32px',height:'32px'}}/></Col>
              </Row>

            ))}
          </Row>
        )
      }

    }
  }
  render(){
    let {dispatch} = this.props;
    let {cartItems,loading,modal2,currentQuantity,modal3,currentItem_id,categoryItem,categoryChildItem,defaultSelectedKeys,isOpen} = this.state;
    if (loading) {
      return (
        <div className="normal">
          <ActivityIndicator toast text="正在加载" animating={true} />
        </div>
      )
    }
    return(
      <div style={{height:"100%",width:'100%',padding:'10px',background:"#fff"}}>
        <div maxLength={8} style={{position:'fixed',top:'2%',left:'10%',width:'80%',zIndex:'100',height:'40px',border:'1px solid #ddd',borderRadius:'15px',background:"#fff"}} onClick={()=>{goToPage({ dispatch, config: { url: "/searchPage" }, isReplace: false })}}>
          <div style={{position:'absolute',top:'25%',left:'5%'}}>
            <img src="image/search_24px.png" style={{width:'24px',height:'24px'}}/><span style={{color:'#C9C9C9',fontSize:'13px'}}>Nome、Codice a barre 名称、条码</span>
          </div>
        </div>
        {isOpen?
          <Row style={{borderBottom:'1px solid #F0F0F0',position:'fixed',top:'10%',left:'34%',width:'66%',background:'#fff',zIndex:'100',padding:'5px 10px 0px',height:'51px'}}>
            {this.sidebarChild3()}
          </Row>:''}

        <div style={{overflow:'hidden',paddingTop:'15%',height:"93%"}}>
          <div style={{float:'left',width:'33%',height:'100%',overflowY:'auto'}}>{this.sidebarMenu()}</div>
          <div style={{float:'left',width:'66%',padding:isOpen?'53px 0px 13px 10px':'7px 0px 13px 10px',height:'100%',overflowY:'auto',}}>
              {this.renderList()}


          </div>
        </div>
        <div style={{position:'fixed',bottom:'0px',left:'0px',width:'100%'}}> <TabBar
          unselectedTintColor="#949494"
          tintColor="#F09600"
          barTintColor="white"
          hidden={this.state.hidden}
        >
          <TabBar.Item
            title="首页"
            key="Life"
            icon={<div style={{
              width: '24px',
              height: '24px',
              background: 'url(image/home2.png) center center /  21px 21px no-repeat' }}
            />
            }
            selectedIcon={<div style={{
              width: '24px',
              height: '24px',
              background: 'url(image/home3.png) center center /  21px 21px no-repeat' }}
            />
            }
            selected={this.state.selectedTab === 'redTab'}
            onPress={() => {
              this.setState({
                selectedTab: 'redTab',
              });
              goToPage({ dispatch, config: { url: "/shop_home" }, isReplace: false })
            }}
            data-seed="logId"
          >

          </TabBar.Item>
          <TabBar.Item
            icon={
              <div style={{
                width: '24px',
                height: '24px',
                background: 'url(image/category.png) center center /  21px 21px no-repeat' }}
              />
            }
            selectedIcon={
              <div style={{
                width: '24px',
                height: '24px',
                background: 'url(image/category1.png) center center /  21px 21px no-repeat' }}
              />
            }
            title="分类"
            key="Koubei"

            selected={this.state.selectedTab === 'blueTab'}
            onPress={() => {
              this.setState({
                selectedTab: 'blueTab',
              });
              goToPage({ dispatch, config: { url: "/category" }, isReplace: false })
            }}
            data-seed="logId1"
          >

          </TabBar.Item>
          <TabBar.Item
            icon={
              <div style={{
                width: '24px',
                height: '24px',
                background: 'url(image/cart4.png) center center /  21px 21px no-repeat' }}
              />
            }
            selectedIcon={
              <div style={{
                width: '24px',
                height: '24px',
                background: 'url(image/cart5.png) center center /  21px 21px no-repeat' }}
              />
            }
            title="购物车"
            key="Friend"
            selected={this.state.selectedTab === 'greenTab'}
            onPress={() => {
              this.setState({
                selectedTab: 'greenTab',
              });
              goToPage({ dispatch, config: { url: "/goodcart" }, isReplace: false });
              localStorage.setItem("cart",'0')
            }}
          >
          </TabBar.Item>
          <TabBar.Item
            icon={{ uri: 'image/my.png' }}
            selectedIcon={{ uri: 'image/my1.png' }}
            title="我的"
            key="my"
            selected={this.state.selectedTab === 'yellowTab'}
            onPress={() => {
              this.setState({
                selectedTab: 'yellowTab',
              });
              goToPage({ dispatch, config: { url: "/my" }, isReplace: false })
            }}
          >
          </TabBar.Item>
        </TabBar></div>
      </div>
    )
  }
}
